package com.controller;

import com.dao.CourseDao;
import com.dto.DTO;
import com.dto.MessageEnum;
import com.entity.Course;
import com.page.PageInfo;
import com.service.CourseService;
import com.utils.GenNumTools;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@CrossOrigin
@Controller //@Controller注解是用spring容器生成 对象 默认对象名 courseController
@RequestMapping("/courseController") //@RequestMapping 用户请求查找该资源使用的名字 网名 默认  /courseController
public class CourseController {


	@Resource
	CourseDao courseDao;

	@Resource
	CourseService courseService;

	@GetMapping("/courses")
	@ResponseBody
	public DTO<Course> editCourse()throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
		return courseService.getAllCourse();
	}


	@RequestMapping("/deleteCourseById/{aId}")
	@ResponseBody
    public DTO<Course> deleteCourseById(@PathVariable("aId") String aId)throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
    	System.out.println(aId+"删除课程");
    	return new DTO<Course>(200, "删除"+aId+"课程成功");
    }


	@RequestMapping("/getCourseByPage")
	@ResponseBody
	public DTO<Course> getCourseByPage(PageInfo pageInfo)throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
		String cacheId = "CourseByPage" + pageInfo.getCurrPage();//自编redis每页数据缓存的key
		System.out.println(cacheId);
		return pageInfo.getCurrPage() > 2 ? courseService.getCoursesByPage(pageInfo) :
				courseService.getCoursesByPage(pageInfo, cacheId);
	}





	@PostMapping("/addCourse")
	@ResponseBody
	public DTO<Course> addCourse(@RequestBody Course course)throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
		System.out.println("增加课程授课");
		course.setCno(GenNumTools.initId("",4,courseDao.getMaxId()));
		Integer result = courseDao.addCourse(course);
		DTO<Course> dto = result > 0 ? new DTO(MessageEnum.GETSTUDENTSUCCESS.getCode(),MessageEnum.GETSTUDENTSUCCESS.getMessage()):
				new DTO(MessageEnum.GETSTUDENTFAIL.getCode(),MessageEnum.GETSTUDENTFAIL.getMessage());
		return dto;
	}

	@PostMapping("/editCourse")
	@ResponseBody
	public DTO<Course> editCourse(@RequestBody Course course)throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
       return courseService.editCourse(course);
	}


}
